package com.kefu.web.im.config.web.router;

import com.kefu.web.im.config.IMDataContext;
import com.kefu.web.im.domain.MessageDataBean;
import com.kefu.web.im.domain.MessageOutContent;
import com.kefu.web.im.domain.SeatService;
import com.kefu.web.im.netty.client.NettyClients;
import com.kefu.web.im.service.quene.ServiceQuene;
import com.kefu.web.im.util.CommonTools;

public class MessageRouter extends Router {

	@Override
	public MessageDataBean handler(MessageDataBean inMessage) {
		MessageOutContent outMessage = new MessageOutContent();
		try {
			outMessage.setOrgi(inMessage.getOrgi());
			outMessage.setFromUser(inMessage.getToUser());
			outMessage.setToUser(inMessage.getFromUser());
			outMessage.setId(CommonTools.genID());
			outMessage.setMessageType(inMessage.getMessageType());
			outMessage.setUser(inMessage.getUser());
			outMessage.setSeatUser(inMessage.getSeatUser());
			/**
			 * 首先交由 IMR处理 MESSAGE指令 ， 如果当前用户是在 坐席对话列表中， 则直接推送给坐席，如果不在，则执行 IMR
			 */
			if (outMessage.getSeatUser() != null && outMessage.getSeatUser().getStatus() != null) {
				if (outMessage.getSeatUser().getStatus().equals(IMDataContext.SeatUserStatusEnum.INQUENE.toString())) {
					int queneIndex = ServiceQuene.getQueneIndex(inMessage.getFromUser(), inMessage.getOrgi(),
							inMessage.getSeatUser().getOrdertime());
					if (IMDataContext.SeatUserStatusEnum.INQUENE.toString()
							.equals(outMessage.getSeatUser().getStatus())) {
						outMessage.setMessage(
								ServiceQuene.getQueneMessage(queneIndex, outMessage.getSeatUser().getChannel()));
					}
				} else if (outMessage.getSeatUser().getStatus()
						.equals(IMDataContext.SeatUserStatusEnum.INSERVICE.toString())) {

				}
			} else if (IMDataContext.MessageTypeEnum.NEW.toString().equals(inMessage.getMessageType())) {
				/**
				 * 找到空闲坐席，如果未找到坐席， 则将该用户放入到 排队队列
				 * 
				 */
				SeatService seatService = ServiceQuene.allotSeat(inMessage.getSeatUser(), inMessage.getOrgi());
				if (seatService != null
						&& IMDataContext.SeatUserStatusEnum.INSERVICE.toString().equals(seatService.getStatus())) {
					outMessage.setMessage(
							ServiceQuene.getSuccessMessage(seatService, inMessage.getSeatUser().getChannel()));
					NettyClients.getInstance().sendSeatEventMessage(seatService.getSeatno(),
							IMDataContext.MessageTypeEnum.NEW.toString(), inMessage.getSeatUser());
				} else {
					int queneIndex = ServiceQuene.getQueneIndex(inMessage.getFromUser(), inMessage.getOrgi(),
							inMessage.getSeatUser().getOrdertime());
					outMessage.setMessage(
							ServiceQuene.getNoSeatMessage(queneIndex, inMessage.getSeatUser().getChannel()));
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return outMessage;
	}

}
